import Vue from 'vue';

/**
 * Vuex状态更新工具（增强版）
 * @param {Object} state - Vuex模块的state对象 
 * @param {Object|Array} payload - 更新载荷
 * @returns {Object} { success: boolean, errors: Array } 操作结果和错误信息 
 */
export default function $setStore(state, payload) {
	// 错误收集器
	const errors = [];
	// 错误记录函数
	const recordError = (type, data, message) => {
		const error = {
			type,
			data,
			message,
			timestamp: new Date().toLocaleString()
		};
		errors.push(error);
		return error;
	};
	// ================== 核心工具函数 ==================
	const setDeepValue = (obj, path, val) => {
		if (typeof path !== 'string' || !path.trim()) {
			console.error('[Vuex]  路径无效', recordError('INVALID_PATH', {
				path,
				val
			}, '路径必须是有效字符串'));
			return false;
		}

		try {
			// 路径标准化处理
			const keys = path.replace(/\[(\w+)\]/g, '.$1').replace(/^\.|\.$/g, '').split('.').filter(Boolean);
			if (!keys.length) {
				console.error('[Vuex]  路径为空', recordError('EMPTY_PATH', {
						path,
						val,
					},
					'路径不能为空'));
				return false;
			}

			const lastKey = keys.pop();
			let current = obj;

			keys.forEach((key, i) => {
				if (!(key in current)) Vue.set(current, key, {});
				else if (typeof current[key] !== 'object' || current[key] === null) {
					const conflictPath = keys.slice(0, i + 1).join('.');
					throw new Error(`路径中断: ${conflictPath} 处遇到非对象类型 (${typeof current[key]})`);
				}
				current = current[key];
			});

			Vue.set(current, lastKey, val);
			return true;
		} catch (e) {
			console.error(`[Vuex]  ${e.message}`, recordError('EXCEPTION', {
					path,
					val,
				},
				e.message));
			return false;
		}
	};

	// ================== 主逻辑处理 ==================
	if (!state || typeof state !== 'object') {
		console.error('[Vuex]  state参数无效', recordError('INVALID_STATE', null, '无效的state对象'));
		return {
			success: false,
			errors
		};
	}

	// 新增空值校验函数 
	const isEmptyPayload = (payload) => {
		if (Array.isArray(payload)) return payload.length === 0;
		if (typeof payload === 'object') return Object.keys(payload).length === 0;
		return !payload; // 其他类型按原逻辑 
	};

	if (isEmptyPayload(payload)) {
		console.error('[Vuex]  payload无效', recordError('EMPTY_PAYLOAD', payload, 'payload包含无效内容'));
		return {
			success: false,
			errors
		};
	}

	try {
		// 动态策略模式替代条件分支
		const updateStrategies = {
			// 格式1：单路径更新 {path:'',value:''}
			SINGLE: () => setDeepValue(state, payload.path, payload.value),
			// 格式2：键值对批量更新 {path1: value1, path2: value2}
			BATCH: () => {
				let allSuccess = true;
				Object.entries(payload).forEach(([p, v]) => {
					if (!setDeepValue(state, p, v)) {
						allSuccess = false;
					}
				});
				return allSuccess;
			},
			// 格式3：数组配置批量更新 [{path:'',value:''}, ...]
			ARRAY: () => {
				let allSuccess = true;
				payload.forEach(item => {
					if (item && item.path !== undefined) {
						if (!setDeepValue(state, item.path, item.value)) {
							allSuccess = false;
						}
					} else {
						// 记录无效的数组项
						recordError('INVALID_ITEM', item, '数组项必须包含path属性');
						allSuccess = false;
					}
				});
				return allSuccess;
			}
		};

		const strategy =
			(payload.path !== undefined) ? 'SINGLE' :
			Array.isArray(payload) ? 'ARRAY' : 'BATCH';

		return {
			success: updateStrategies[strategy](),
			errors
		};
	} catch (e) {
		console.error(`[Vuex]  全局错误: ${e.message}`, recordError('GLOBAL_ERROR', payload, e.message));
		return {
			success: false,
			errors
		};
	}
}